package com.wephone.Student.ui;

import java.util.HashMap;
import java.util.Map;

import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.text.TextUtils;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.widget.EditText;
import android.widget.Toast;

import com.easemob.EMCallBack;
import com.easemob.chat.EMChat;
import com.easemob.chat.EMChatManager;
import com.easemob.chat.EMGroupManager;
import com.easemob.exceptions.EaseMobException;
import com.easemob.util.HanziToPinyin;
import com.loopj.android.http.RequestParams;
import com.umeng.socialize.bean.SHARE_MEDIA;
import com.umeng.socialize.bean.SocializeEntity;
import com.umeng.socialize.bean.SocializeUser;
import com.umeng.socialize.bean.StatusCode;
import com.umeng.socialize.controller.UMServiceFactory;
import com.umeng.socialize.controller.UMSocialService;
import com.umeng.socialize.controller.listener.SocializeListeners.FetchUserListener;
import com.umeng.socialize.controller.listener.SocializeListeners.SnsPostListener;
import com.umeng.socialize.controller.listener.SocializeListeners.SocializeClientListener;
import com.umeng.socialize.controller.listener.SocializeListeners.UMAuthListener;
import com.umeng.socialize.exception.SocializeException;
import com.umeng.socialize.media.UMImage;
import com.umeng.socialize.sso.UMQQSsoHandler;
import com.umeng.socialize.weixin.controller.UMWXHandler;
import com.wephone.Student.BaseApplication;
import com.wephone.Student.R;
import com.wephone.Student.WelcomeActivity;
import com.wephone.Student.bean.LoginResponse;
import com.wephone.Student.huanxin.Constant;
import com.wephone.Student.huanxin.domain.User;
import com.wephone.Student.network.HttpClient;
import com.wephone.Student.network.MyResponseHandler;
import com.wephone.Student.util.Constants;
import com.wephone.Student.util.MD5;
import com.wephone.Student.util.ShareReferenceUtil;
import com.wephone.Student.util.Util;

public class LoginActivity extends BaseActivity{
	private EditText userNameEdit;
	private EditText passwordEdit;
	private String uPlatform;
	private String uPlatformid;
	private UMSocialService mController;

	private MyResponseHandler getHandler(){
		MyResponseHandler handler = new MyResponseHandler(LoginActivity.this,LoginResponse.class){
			@Override
			public void onSuccess(String result) {
				super.onSuccess(result);
				
				if(getDataSuccess){
					LoginResponse res = (LoginResponse)response;
					if(res.getResult()!=null && res.getResult().equals("UserNotExist")){
						new AlertDialog.Builder(LoginActivity.this)
						.setTitle("提示")
						.setMessage("请完善资料已完成注册")
						.setNegativeButton("取消", new DialogInterface.OnClickListener() {
							@Override
							public void onClick(DialogInterface dialog, int which) {
							}
						})
						.setPositiveButton("确定", new DialogInterface.OnClickListener() {
							public void onClick(DialogInterface dialog, int whichButton) {
								if(uPlatform==null){
									startActivity(new Intent(getApplicationContext(),NewRegisterActivity1.class));
									finish();
								}else{
									if(uPlatform.equals("sina1")){
										mController.login(getApplicationContext(), SHARE_MEDIA.SINA,new SocializeClientListener() {
											 @Override
											 public void onStart() {
												 Log.d("111","2222");
											 }
											 
											 @Override
											 public void onComplete(int status, SocializeEntity entity) {
												 mController.getUserInfo(LoginActivity.this, new FetchUserListener() {
														@Override
														public void onStart() {
														}
														@Override
														public void onComplete(int status, SocializeUser user) {
															if(user!=null && user.mLoginAccount!=null){
																// 可以从 user 中获取用户信息
																Bundle bundle = new Bundle();
																bundle.putString("uPlatform", uPlatform);
																bundle.putString("uPlatformid", uPlatformid);
																bundle.putString("gender", user.mLoginAccount.getGender().toString());
																bundle.putString("username", user.mLoginAccount.getUserName());
																startActivity(new Intent(getApplicationContext(),NewRegisterActivity1.class).putExtras(bundle));
																finish();
															}
														} 
													});
											 	}
										 });
									}else{
										Bundle bundle = new Bundle();
										bundle.putString("uPlatform", uPlatform);
										bundle.putString("uPlatformid", uPlatformid);
										startActivity(new Intent(getApplicationContext(),NewRegisterActivity1.class).putExtras(bundle));
										finish();
									}
								}
							}
						}).show();
					}else if(res.getData()!=null){
						BaseActivity.infoData = res.getData();
						ShareReferenceUtil.saveUserId(getApplicationContext(), res.getData().getuId());
						String infoJson = gson.toJson(BaseActivity.getMyInfo(getApplicationContext()));
						ShareReferenceUtil.saveUserInfoJson(getApplicationContext(), infoJson);
//						setAliasAndTags(ShareReferenceUtil.getUserId(getApplicationContext()));
						//reg push
//						RequestParams params = new RequestParams();
//						params.put("uId", BaseActivity.getMyInfo(getApplicationContext()).getuId());
//						params.put("uPushIdentifier", ShareReferenceUtil.getUserPushId(getApplicationContext()));
//						HttpClient.getInstance().get(Constants.API_REG_PUSH_URL, params, getHandler2());
						
						//login huanxin account
//						System.out.println("-----infoData.getuId()-----"+infoData.getuId());
//						System.out.println("-----infoData.getuPwd()-----"+infoData.getuPwd());
						EMChatManager.getInstance().login(infoData.getuId(), infoData.getuPwd(), new EMCallBack() {
							@Override
							public void onError(int arg0, final String errorMsg) {
								runOnUiThread(new Runnable() {
									public void run() {
										Toast.makeText(LoginActivity.this, "登录聊天服务器失败，您将收不到消息", Toast.LENGTH_SHORT).show();
									}
								});
							}

							@Override
							public void onProgress(int arg0, String arg1) {
							}

							@Override
							public void onSuccess() {
								// 登陆成功，保存用户名密码
								BaseApplication.getInstance().setUserName(infoData.getuId());
								BaseApplication.getInstance().setPassword(infoData.getuPwd());
								runOnUiThread(new Runnable() {
									public void run() {
										EMGroupManager.getInstance().loadAllGroups();
										EMChatManager.getInstance().loadAllConversations();
										
									}
								});
								processContactsAndGroups();	
//								try {
//									// demo中简单的处理成每次登陆都去获取好友username，开发者自己根据情况而定
//									List<String> usernames = EMChatManager.getInstance().getContactUserNames();
//									System.out.println("-----usernames.size()-----"+usernames.size());
//									Map<String, User> userlist = new HashMap<String, User>();
//									for (String username : usernames) {
//										User user = new User();
//										user.setUsername(username);
//										setUserHearder(username, user);
//										userlist.put(username, user);
//									}
//									// 添加user"新的朋友"
////									User newFriends = new User();
////									newFriends.setUsername(Constant.NEW_FRIENDS_USERNAME);
////									newFriends.setNick("新的朋友");
////									newFriends.setHeader("");
////									userlist.put(Constant.NEW_FRIENDS_USERNAME,newFriends);
//									//添加"群聊"
////									User groupUser = new User();
////									groupUser.setUsername(Constant.GROUP_USERNAME);
////									groupUser.setNick("群聊");
////									groupUser.setHeader("");
////									userlist.put(Constant.GROUP_USERNAME, groupUser);
//									
//									//存入内存
//									BaseApplication.getInstance().setContactList(userlist);
//									// 存入db
//									UserDao dao = new UserDao(LoginActivity.this);
//									List<User> users = new ArrayList<User>(userlist.values());
//									dao.saveContactList(users);
//
//									// 获取群聊列表,sdk会把群组存入到EMGroupManager和db中
//									EMGroupManager.getInstance().getGroupsFromServer();
//								} catch (Exception e) {
//									e.printStackTrace();
//								}
								EMChat.getInstance().setAppInited();
//								
//								runOnUiThread(new Runnable() {
//									public void run() {
//										Toast.makeText(LoginActivity.this, "登录聊天服务器成功", Toast.LENGTH_SHORT).show();
//									}
//								});
							}
						});
						//app初始化完毕
//						EMChat.getInstance().setAppInited();
//						startActivity(new Intent(getApplicationContext(),MainTabBar.class));
//						finish();
						
						//登录分享
						if(uPlatform!=null){
							if(uPlatform.equals("sina")){
								mController.setShareContent(Constants.LOGIN_SHARE_TEXT);
								mController.setShareMedia(new UMImage(getApplicationContext(), R.drawable.login_share_image));
								mController.directShare(getApplicationContext(), SHARE_MEDIA.SINA,new SnsPostListener() {
							            @Override
							            public void onStart() {
//							                Toast.makeText(getApplicationContext(), "分享开始",Toast.LENGTH_SHORT).show();
							            }

							            @Override
							            public void onComplete(SHARE_MEDIA platform,int eCode, SocializeEntity entity) {
							                if(eCode == StatusCode.ST_CODE_SUCCESSED){
//							                    Toast.makeText(getApplicationContext(), "分享成功",Toast.LENGTH_SHORT).show();
							                }else{
//							                    Toast.makeText(getApplicationContext(), "分享失败",Toast.LENGTH_SHORT).show();
							                }
							            }
							    });
							}
//							else if(uPlatform.equals("qq")){
//								mController.setShareContent(Constants.LOGIN_SHARE_TEXT);
//								mController.setShareMedia(new UMImage(getApplicationContext(), R.drawable.login_share_image));
//								mController.directShare(getApplicationContext(), SHARE_MEDIA.QQ,new SnsPostListener() {
//							            @Override
//							            public void onStart() {
////							                Toast.makeText(getApplicationContext(), "分享开始",Toast.LENGTH_SHORT).show();
//							            }
//
//							            @Override
//							            public void onComplete(SHARE_MEDIA platform,int eCode, SocializeEntity entity) {
//							                if(eCode == StatusCode.ST_CODE_SUCCESSED){
////							                    Toast.makeText(getApplicationContext(), "分享成功",Toast.LENGTH_SHORT).show();
//							                }else{
////							                    Toast.makeText(getApplicationContext(), "分享失败",Toast.LENGTH_SHORT).show();
//							                }
//							            }
//							    });
//							}else if(uPlatform.equals("weixin")){
//								mController.setShareContent(Constants.LOGIN_SHARE_TEXT);
//								mController.setShareMedia(new UMImage(getApplicationContext(), R.drawable.login_share_image));
//								mController.directShare(getApplicationContext(), SHARE_MEDIA.WEIXIN,new SnsPostListener() {
//							            @Override
//							            public void onStart() {
////							                Toast.makeText(getApplicationContext(), "分享开始",Toast.LENGTH_SHORT).show();
//							            }
//
//							            @Override
//							            public void onComplete(SHARE_MEDIA platform,int eCode, SocializeEntity entity) {
//							                if(eCode == StatusCode.ST_CODE_SUCCESSED){
////							                    Toast.makeText(getApplicationContext(), "分享成功",Toast.LENGTH_SHORT).show();
//							                }else{
////							                    Toast.makeText(getApplicationContext(), "分享失败",Toast.LENGTH_SHORT).show();
//							                }
//							            }
//							    });
//							}
						}
						
						startActivity(new Intent(getApplicationContext(),MainTabBar.class).setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | 
				                Intent.FLAG_ACTIVITY_CLEAR_TASK |
				                Intent.FLAG_ACTIVITY_NEW_TASK));
						finish();
					}else{
						Toast.makeText(getApplicationContext(), res.getErrorMsg(), Toast.LENGTH_SHORT).show();
					}
				}
			}
		};
		return handler;
	}
	private void processContactsAndGroups(){
		
	 // 获取群聊列表(群聊里只有groupid和groupname等简单信息，不包含members),sdk会把群组存入到内存和db中
        try {
			EMGroupManager.getInstance().getGroupsFromServer();
			Map<String, User> userlist = new HashMap<String, User>();
	 
	        // 添加user"申请与通知"
	        User newFriends = new User();
	        newFriends.setUsername(Constant.NEW_FRIENDS_USERNAME);
	        String strChat = "系统消息";
	        newFriends.setNick(strChat);

	        userlist.put(Constant.NEW_FRIENDS_USERNAME, newFriends);
	        
	        BaseApplication.getInstance().setContactList(userlist);
		} catch (EaseMobException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_login);
		
		init();
		
	}

	private void init(){
		userNameEdit = (EditText)findViewById(R.id.username_edit);
		passwordEdit = (EditText)findViewById(R.id.password_edit);
		
		findViewById(R.id.btn_back).setOnClickListener(new View.OnClickListener() {
			@Override
			public void onClick(View v) {
				startActivity(new Intent(getApplicationContext(),WelcomeActivity.class));
				finish();
			}
		});
		findViewById(R.id.btn_login).setOnClickListener(new View.OnClickListener() {
			@Override
			public void onClick(View v) {
//				startActivity(new Intent(getApplicationContext(),MainTabBar.class));
				
				if(TextUtils.isEmpty(userNameEdit.getText().toString())){
					Toast.makeText(getApplicationContext(), "邮箱必须填写", Toast.LENGTH_SHORT).show();
					return;
				}
				if(TextUtils.isEmpty(passwordEdit.getText().toString())){
					Toast.makeText(getApplicationContext(), "密码必须填写", Toast.LENGTH_SHORT).show();
					return;
				}
				if(!Util.checkEmail((userNameEdit.getText().toString()))){
					Toast.makeText(getApplicationContext(), "邮箱格式不正确", Toast.LENGTH_SHORT).show();
					return;
				}
//				System.out.println("---md5 pwd---"+MD5.md5(passwordEdit.getText().toString()));
				RequestParams params = new RequestParams();
				params.put("uEmail", userNameEdit.getText().toString());
				params.put("uPwd", MD5.md5(passwordEdit.getText().toString()));
				params.put("loginType", "0");
				HttpClient.getInstance().get(Constants.API_USER_LOGIN_URL, params, getHandler());
			}
		});
		findViewById(R.id.btn_finish).setOnClickListener(new View.OnClickListener() {
			@Override
			public void onClick(View arg0) {
				//startActivity(new Intent(getApplicationContext(),RegisterActivity.class));
				startActivity(new Intent(getApplicationContext(),NewRegisterActivity1.class));
				finish();
			}
		});
		
		findViewById(R.id.login_type_1).setOnClickListener(new View.OnClickListener() {
			@Override
			public void onClick(View v) {
				doThirdAuth(SHARE_MEDIA.SINA,0);
			}
		});
		findViewById(R.id.login_type_2).setOnClickListener(new View.OnClickListener() {
			@Override
			public void onClick(View v) {
				doThirdAuth(SHARE_MEDIA.QQ,1);
			}
		});
		findViewById(R.id.login_type_5).setOnClickListener(new View.OnClickListener() {
			@Override
			public void onClick(View v) {
				doThirdAuth(SHARE_MEDIA.WEIXIN,2);
			}
		});
//		findViewById(R.id.login_type_4).setOnClickListener(new View.OnClickListener() {
//			@Override
//			public void onClick(View v) {
//				doThirdAuth(SHARE_MEDIA.FACEBOOK,3);
//			}
//		});
		
		findViewById(R.id.find_password_iv).setOnClickListener(new View.OnClickListener() {
			@Override
			public void onClick(View v) {
				new AlertDialog.Builder(LoginActivity.this)
				.setTitle("提示")
				.setMessage("请使用您的注册邮箱发送重置密码请求至liu_xue_sheng@163.com我们将为您把密码重置为123456")
				.setPositiveButton("确定", null).show();
			}
		});
	}
	
	private void doThirdAuth(final SHARE_MEDIA media,final int type){
//		System.out.println("-----doThirdAuth-----"+type);
		mController = UMServiceFactory.getUMSocialService("com.umeng.share");
		
//		// 添加腾讯微博SSO授权
//		mController.getConfig().setSsoHandler(new TencentWBSsoHandler());
		addQQPlatform();
		addWXPlatform();
		mController.doOauthVerify(LoginActivity.this, media, new UMAuthListener(){
			@Override
			public void onCancel(SHARE_MEDIA platform) {
			}

			@Override
			public void onComplete(Bundle value, SHARE_MEDIA platform) {
				// TODO Auto-generated method stub
				String uid = value.getString("uid");
//				System.out.println("-----uid-----"+uid);
				RequestParams params = new RequestParams();
				if(type==0){
					uPlatform = "sina";
					params.put("uPlatform", uPlatform);
				}else if(type==1){
					uPlatform = "qq";
					params.put("uPlatform", uPlatform);
				}else if(type==2){
					uPlatform = "weixin";
					params.put("uPlatform", uPlatform);
//				}else if(type==3){
//					uPlatform = "facebook";
//					params.put("uPlatform", uPlatform);
				}
				uPlatformid = uid;
				params.put("uPlatformid", uPlatformid);
				params.put("loginType", "1");
				HttpClient.getInstance().get(Constants.API_USER_LOGIN_URL, params, getHandler());
			}

			@Override
			public void onError(SocializeException e,SHARE_MEDIA platform) {
			}

			@Override
			public void onStart(SHARE_MEDIA platform) {
				Toast.makeText(getApplicationContext(), "授权开始", Toast.LENGTH_SHORT).show();
			}});
	}
	
	private void addQQPlatform() {
		String appId = "100530288";
		String appKey = "2042fd761ebf8495387ed78cc81b0b40";
		// 添加QQ支持, 并且设置QQ分享内容的target url
		UMQQSsoHandler qqSsoHandler = new UMQQSsoHandler(LoginActivity.this,
				appId, appKey);
		qqSsoHandler.setTargetUrl("http://www.imlxs.com");
		qqSsoHandler.addToSocialSDK();
	}
	
	private void addWXPlatform() {
		// 注意：在微信授权的时候，必须传递appSecret
		// wx967daebe835fbeac是你在微信开发平台注册应用的AppID, 这里需要替换成你注册的AppID
		String appId = "wx035b9a7450e44f5e";
		String appSecret = "9d59ffbef758410ae191ec756210b75b";
		// 添加微信平台
		UMWXHandler wxHandler = new UMWXHandler(LoginActivity.this,
				appId,appSecret);
		wxHandler.addToSocialSDK();

		// 支持微信朋友圈
		UMWXHandler wxCircleHandler = new UMWXHandler(LoginActivity.this,
				appId, appSecret);
		wxCircleHandler.setToCircle(true);
		wxCircleHandler.addToSocialSDK();
	}
	
	@Override
	public boolean onKeyDown(int keyCode, KeyEvent event) {
		if (keyCode == KeyEvent.KEYCODE_BACK && event.getRepeatCount() == 0) {
			startActivity(new Intent(getApplicationContext(),WelcomeActivity.class));
			finish();
			return true; 
       }
       return super.onKeyDown(keyCode, event);
	}

	/**
	 * 设置hearder属性，方便通讯中对联系人按header分类显示，以及通过右侧ABCD...字母栏快速定位联系人
	 * 
	 * @param username
	 * @param user
	 */
	protected void setUserHearder(String username, User user) {
		String headerName = null;
		if (!TextUtils.isEmpty(user.getNick())) {
			headerName = user.getNick();
		} else {
			headerName = user.getUsername();
		}
		if (username.equals(Constant.NEW_FRIENDS_USERNAME)) {
			user.setHeader("");
		} else if (Character.isDigit(headerName.charAt(0))) {
			user.setHeader("#");
		} else {
			user.setHeader(HanziToPinyin.getInstance().get(headerName.substring(0, 1)).get(0).target.substring(0, 1).toUpperCase());
			char header = user.getHeader().toLowerCase().charAt(0);
			if (header < 'a' || header > 'z') {
				user.setHeader("#");
			}
		}
	}

	
}
